package com.lingxin.gps.wap.command;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingxin.gps.sdk.GpsDeviceApi;
import com.lingxin.gps.sdk.GpsDeviceUtil;
import com.pisces.core.Assert;
import com.pisces.core.BaseCommand;
import com.pisces.core.BizException;
import com.pisces.tool.query.QueryObject;

import java.util.List;
import java.util.regex.Pattern;

/**
 *
 */
public class CDeviceTrack extends BaseCommand {

	private static final Pattern PATTERN_DATE_TIME = Pattern
			.compile("^(\\d{4})-(0\\d{1}|1[0-2])-(0\\d{1}|[12]\\d{1}|3[01]) (0\\d{1}|1\\d{1}|2[0-3]):[0-5]\\d{1}$");

	/**
	 * 设备号
	 */
	private String deviceCode;
	/**
	 * 开始时间
	 */
	private String startTime;
	/**
	 * 结束时间
	 */
	private String endTime;
	/**
	 * 播放速度
	 */
	private int speed;

	private Long uid;
	private String token;

	@Override
	public void init() throws Exception {
		deviceCode = getPara("deviceCode");
		Assert.notBlank(deviceCode, "设备号不能为空");

		startTime = getPara("startTime");
		Assert.notBlank(startTime, "开始时间不能为空");
		if (!PATTERN_DATE_TIME.matcher(startTime).matches()) {
			throw new BizException("开始时间不正确");
		}

		endTime = getPara("endTime");
		Assert.notBlank(endTime, "结束时间不能为空");
		if (!PATTERN_DATE_TIME.matcher(endTime).matches()) {
			throw new BizException("结束时间不正确");
		}

		speed = getParaToInt("speed");

		uid = context.getAttr("uid");
		token = context.getAttr("token");
	}

	@Override
	public void doCommand() throws Exception {
		QueryObject queryObject = new QueryObject();
		queryObject.addQuery("startTime", startTime);
		queryObject.addQuery("endTime", endTime);
		if(speed > 0){
			queryObject.addQuery("speed", speed);
		}

		JSONObject resData = GpsDeviceApi.deviceTrack(uid, token, deviceCode, queryObject);
		//data.put("track", resData.getJSONArray("track"));
		List<JSONObject> list = JSON.parseArray(resData.getString("track"), JSONObject.class);
		Assert.moreThanZero(list.size(), "当前时段暂无轨迹");

		JSONArray track = new JSONArray();
		for(JSONObject info : list){
			if(GpsDeviceUtil.validateCoordinate(info.getString("coordinate"))){
				track.add(GpsDeviceUtil.transCoordinate(info.getString("coordinate")));
			}
		}
//		track.add(new Double[]{118.6053, 24.903949});
//		track.add(new Double[]{118.6253, 24.873949});
//		track.add(new Double[]{118.6553, 24.893949});
//		track.add(new Double[]{118.6153, 24.823949});
//		track.add(new Double[]{118.5853, 24.873949});
		data.put("track", track);

		if(speed == 10){
			// 快速
			speed = 120;
		}else if(speed == 20){
			// 中速
			speed = 60;
		}else if(speed == 30){
			// 低速
			speed = 30;
		}else{
			// 默认中速
			speed = 60;
		}
		data.put("speed", speed);
		data.put("deviceCode", deviceCode);
		//设备图标
		data.put("deviceIcon", "/static/themes/images/car/car_red.png");
		//data.put("deviceIcon", "http://webapi.amap.com/ui/1.0/ui/misc/PathSimplifier/examples/imgs/plane.png");

	}

}
